
from views import *
from google.appengine.api import images

def getfoto(request, product_id):
    producte = Product.get_by_id(int(product_id))
    return http.HttpResponse( producte.foto, 'text' )

def new_product(request, cope_id):
    return edit_product(request, cope_id, None)

def edit_product(request, cope_id, product_id):
    """Create or edit a gift.  GET shows a blank form, POST processes it."""
    user = users.GetCurrentUser()
    if user is None:
      return http.HttpResponseForbidden('You must be signed in to add or edit a ')

    productors = db.GqlQuery('SELECT * FROM Productor')
    product = None
    if product_id:
      product = Product.get(db.Key.from_path(Product.kind(), int(product_id)))
      if product is None:
        return http.HttpResponseNotFound('No product exists with that key (%r)' %
                                         product_id)


    # Es una edicio pura i dura
    if not request.POST:
      return respond(request, user, 'product', {'product': product, 'productors':productors})

    # Ara s'ha de guardar

    if product is None:
      product = Product(name=request.POST['name'])
    product.name = request.POST['name']

    if request.FILES.has_key('file'):
      foto = db.Blob(request.FILES.get('file')['content'])
      #img = images.Image(foto)  
      #img.resize(width=500, height=200)  
      #img.im_feeling_lucky()
      #product.foto = img.execute_transforms(output_encoding=images.JPEG)
      product.foto = foto
      
    productor = Productor.get(request.POST['productor'])
    if request.POST.has_key('actiu'):
      product.actiu = True
    else:
      product.actiu = False
    product.productor = productor
    product.description = request.POST['descripcio']
    product.price = float(request.POST['price'])
    product.coperativa = Coperativa.get_by_id(int(cope_id))
    product.owner = user
    product.save()

    return http.HttpResponseRedirect('/editcope/%s' % cope_id)
